module.exports = class extends think.Model {
  constructor(...args) {
    super(...args);
    this.relation = {
      member: {
        type: think.Model.HAS_ONE, model: 'user_member', // 会员信息表，垂直分割，与user表1-1对应
        key: 'uid', fKey: 'uid', field: 'puid,invitation_code',
      },
    };
  }
  
  async getTags(uid) {
    return await this.model('user_tag').alias('tag').join({
      table: 'user_tag_link',
      join: 'left',
      as: 'link',
      on: ['tag.id', 'link.tag_id'],
    }).join({
      table: 'user', join: 'left', as: 'user', on: ['user.id', 'link.uid'],
    }).where({'user.id': uid}).field('tag.id,tag.title').select();
  }
  
  async getRoles(uid) {
    return await this.model('role').alias('r').join({
      table: 'user_role', join: 'left', as: 'ur', on: ['r.id', 'ur.role_id'], // field:'uid'
    }).where({'ur.uid': uid}).field('id,name,title').select();
  }
  
  // 验证密码
  verifyPassword(userInfo, password) {
    // return think.md5(think.md5(password) + userInfo.encrypt) ===
    // userInfo.password;
    return think.service('utils').getEncryptPassword(password, userInfo.encrypt) === userInfo.password;
  }
  
  async deleteTag(uid, tagId) {
    return await think.model('user_tag_link').
    where({uid: uid, tag_id: tagId}).
    delete();
  }
  
  async addTag(uid, tagId) {
    const result = await think.model('user_tag_link').thenAdd({uid: uid, tag_id: tagId}, {uid: uid, tag_id: tagId});
    return result.id;
  }
  
  async addUser(data) {
    // 1、在user主表增加记录
    // 2、在user_member表增加记录
    // 3、设置默认的角色为default
    
    await this.startTrans();
    
    const uid = await this.add(data); // uid
    if (!uid) {
      await this.rollback();
      return false;
    }
    
    const member = {};
    member['uid'] = uid;
    member['puid'] = 0;
    
    // 计算邀请码，邀请码不能重复
    const utils = think.service('utils');
    
    let invitation_code = utils.getRamdomString(6,
        {letters: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', numbers: true});
    while (this.where({invitation_code: invitation_code}).count() > 0) {
      invitation_code = exports.getRamdomString(6,
          {letters: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', numbers: true});
    }
    member['invitation_code'] = invitation_code;
    
    // 由于事务里的操作需要在同一个连接里执行，如果处理过程中涉及多个模型的操作，需要多个模型复用同一个数据库连接，这时可以通过 model.db
    // 方法达到复用数据库连接的效果。
    const memberModel = this.model('user_member').db(this.db());
    const member_id = await memberModel.thenAdd(member, {uid: uid});
    
    if (!member_id) {
      await this.rollback();
      return false;
    }
    
    let role_id = 1;//默认角色为"default"
    //添加默认角色
    const userRoleId = await this.model('user_role').
    db(this.db()).
    thenAdd({uid: uid, role_id: role_id}, {
      uid: uid, role_id: role_id,
    });
    if (!userRoleId) {
      await this.rollback();
      return false;
    }
    
    await this.commit();
    return uid;
  }
};
